<template>
  <div class="addImages">
    <input
      type="file"
      class="file"
      id="fileInput"
      @change="getFileHead($event)"
      accept="image/png, image/jpeg, image/gif, image/jpg"
    />
    <div class="text-detail" v-if="'' === this.imgHead">
      <span>+</span>
      <p>点击上传</p>
    </div>
    <div class="imgs" v-if="'' !== this.imgHead">
      //绑定图片
      <img :src="imgHead" width="160px" height="125px" />
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imgHead: "",
    };
  },
  methods: {
    getFileHead(event) {
      this.file = event.target.files[0];
      //创建 formData 对象
      let formData = new FormData();
      // 向 formData 对象中添加文件
      formData.append("file", this.file);
      //封装axios方法
      this.axios.post("/user/upload", formData).then((response) => {
        this.imgHead = response.data.url;
        console.log(this.imgHead);
      });
    },
  },
};
</script>

<style scoped>
.addImages {
  display: inline-block;
  width: 160px;
  height: 125px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  border: 1px dashed darkgray;
  background: #f8f8f8;
  position: relative;
  overflow: hidden;
}
.text-detail {
  margin-top: 40px;
  text-align: center;
}
.text-detail > span {
  font-size: 40px;
}
.file {
  position: absolute;
  top: 0;
  left: 0;
  width: 140px;
  height: 125px;
  opacity: 0;
}
</style>